package net.maku.newbase;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.SneakyThrows;
import net.maku.framework.mybatis.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.util.List;

public class NewBaseServiceImpl<M extends BaseMapper<T>, T> extends BaseServiceImpl<M, T> {

    @Autowired
    protected M dao;

    /**
     * 自由的mapper
     * <hr>
     * 缺少约束，谨慎使用
     */
    @Autowired
    protected FreedomMapper freedomMapper;

    public <E> List<E> jsonToEntity(Object o, Class<E> e) {
        return JSONArray.parseArray(JSONArray.toJSONString(o), e);
    }

    public <E> List<E> jsonToEntity(List list, Class<E> e) {
        return JSONArray.parseArray(JSONArray.toJSONString(list), e);
    }

    /**
     * json 转换实体对象
     *
     * @param page
     * @param rClass
     * @param <R>
     * @return
     */
    protected <R> IPage<R> fn(IPage page, Class<R> rClass) {
        if (page.getTotal() == 0) {
            return page;
        }

        page.setRecords(jsonToEntity(page.getRecords(), rClass));
        return page;
    }

    @SneakyThrows
    protected String sqlVO(String sql, Object vo) {
        Class exampleObjectClass = vo.getClass();
        Field[] fields = exampleObjectClass.getDeclaredFields();
        for (Field fi : fields) {
            fi.setAccessible(true);
            Object str = fi.get(vo);
            sql = sql.replaceAll("#\\{" + fi.getName() + "}", str + "");
        }
        return sql;
    }

}
